const fs = require("fs");
const sugar = loader('sugar')
const path = require("path")
file_list=[];
// 核心文件的监控
module.exports=function(){
  file_list.push(sugar.path("/gem.config.js"));
  fs.watchFile(sugar.path("/gem.config.js"),{
    interval:100,persistent:false
  },(cur, prv) => {
    //核心配置被改动了，核心配置涉及到路由文件
    console.log('核心配置被更改，重载配置，如效果未更改请重启服务');
    //重载配置
    global.gem_config = loader("/gem.config.js",true);
  })
  //监控核心文件夹
  start(__dirname);
  global.monitor[__filename]={stop};
}


function start(filepath){
  fs.readdirSync(filepath).forEach(res=>{
    if(fs.lstatSync(path.resolve(filepath,res)).isDirectory() && res!=="monitor"){
      //是文件夹
      start(path.resolve(filepath,res));
    }else{
      file_list.push(path.resolve(filepath,res));
      //是一个文件，进行监控
      fs.watchFile(path.resolve(filepath,res),{
        interval:100,persistent:false
      },(cur, prv) => {
        global.clear();
        console.log('\033[30;43m CONDUCT \033[40;33m Compilation... '+res)
        console.time('\033[42;30m DONE \033[40;32m Compiled successfully in ');
        //清理缓存
        loader(path.resolve(filepath,res),true);
        global.clear();
        console.timeEnd('\033[42;30m DONE \033[40;32m Compiled successfully in ');
        console.log();
      })
    }
  })
}



function stop(){
  delete global.monitor[__filename];
  file_list.forEach(file=>{
    //关闭文件监控
    fs.unwatchFile(file);
  })
  file_list=[];
  //清理当前文件缓存
  delete require.cache[__filename];
  return __filename;
}